package org.example.demo.controller;

import org.example.demo.dto.ShipmentDTO;
import org.example.demo.model.CommonResponse;
import org.example.demo.service.backend.ShipmentBackendService;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigInteger;

@RestController
@RequestMapping("/shipment")
public class ShipmentController {

    @Autowired
    private ShipmentBackendService shipmentBackendService;

    // 添加物流信息
    @PostMapping("/add")
    public CommonResponse addShipment(
            @RequestParam int id,
            @RequestParam int carrier,
            @RequestParam String from,
            @RequestParam String to) {
        
        ShipmentDTO shipmentDTO = new ShipmentDTO();
        shipmentDTO.setId(new BigInteger(String.valueOf(id)));
        shipmentDTO.setCarrier(new BigInteger(String.valueOf(carrier)));
        shipmentDTO.setFrom(from);
        shipmentDTO.setTo(to);
        
        boolean ok = shipmentBackendService.addShipment(shipmentDTO);
        if (ok) {
            return CommonResponse.ok(ok);
        }

        return CommonResponse.fail("4001", new Exception("添加物流信息失败"));
    }

    // 获取物流信息
    @PostMapping("/get")
    public CommonResponse getShipment(@RequestParam int id) throws ContractException {
        
        ShipmentDTO shipmentDTO = shipmentBackendService.getShipment(id);
        if (shipmentDTO != null) {
            return CommonResponse.ok(shipmentDTO);
        }

        return CommonResponse.fail("4001", new Exception("获取物流信息失败"));
    }

    // 更新物流状态
    @PostMapping("/updateStatus")
    public CommonResponse updateShipmentStatus(@RequestParam int id, @RequestParam String status) {
        
        boolean ok = shipmentBackendService.updateShipmentStatus(id, status);
        if (ok) {
            return CommonResponse.ok(ok);
        }

        return CommonResponse.fail("4001", new Exception("更新物流状态失败"));
    }

    // 获取物流状态
    @PostMapping("/getStatus")
    public CommonResponse getStatus(@RequestParam int id) throws ContractException {
        
        String status = shipmentBackendService.getStatus(id);
        if (status != null) {
            return CommonResponse.ok(status);
        }

        return CommonResponse.fail("4001", new Exception("获取物流状态失败"));
    }
}
